package com.shouhuobao.take.mine;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.iseastar.dianxiaosan.coupon.CouponListActivity;
import com.iseastar.dianxiaosan.stamp.StampStoreActivity;
import com.iseastar.guojiang.BaseFragment;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.AppLogic;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.shouhuobao.station.R;
import com.shouhuobao.station.wxapi.Constants;
import com.shouhuobao.take.invite.StationInviteActivity;
import com.shouhuobao.take.recharge.SmsReChargeActivity;
import com.shouhuobao.take.utils.StringUtils;
import com.shouhuobao.take.verify.MyStationInfoActivity;
import com.shouhuobao.take.wallet.MyWalletActivity;
import com.shouhuobao.take.weight.CircularImage;

import droid.frame.activity.title.TitleRes;
import droid.frame.ui.dialog.BaseDialog;
import droid.frame.utils.GlideUtil;
import droid.frame.utils.android.SharedPref;
import droid.frame.utils.http.BitmapUtils;
import droid.frame.utils.lang.Str;

/**
 * 裹儿联盟、我的
 *
 * @author coffee<br>
 * 2017年6月30日下午4:52:07
 */
public class MyFragment extends BaseFragment implements OnClickListener {

    private Handler mhandler;
    private boolean isRequest2get = true;
    //代收统计信息
    private TextView mCount1, mCount2, mCount3, mCount4;
    //寄件统计信息
    private TextView mTodaySendTV, mMonthSendTV, mTotalSendTV;
    private TextView mVersion;
    private TextView mAccountMoney;
    //驿站头像
    private CircularImage mStorePhotoIV;
    //邮票商城
    private View mStampShop;
    //我的邮票
    private View mMyStamp;
    private String smsRemainCount = null;
    private String accountMoneyStr = "账户余额:  %1$s元";

    private BaseDialog baseDialog = null;
    //用于保存网络加载的图片
    private String photoUrl = "";
    //用于保存本地的图片
    private String localPhotoUrl = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mhandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                isRequest2get = true;//
            }
        };

    }

    @Override
    public void onResume() {
        super.onResume();
        if (isRequest2get) {
            AppHttp.getInstance().takeQueryCount();
        }
        setStationLevel();
        isRequest2get = false;
        mhandler.removeMessages(1);
        mhandler.sendEmptyMessageDelayed(1, 1000 * 10);// 10秒钟内只查询一次
    }

    protected void findViewById() {
        setContentView(R.layout.my_setting);
        super.findViewById();
        getAppTitle().setTitle(null, new TitleRes("我的"), new TitleRes(R.drawable.person_shezhi, new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivityContext(), MySettingsActivity.class));
            }
        }));
        //驿站余额
        mAccountMoney = (TextView) findViewById(R.id.person_account_money);
        // 代收统计信息
        mCount1 = (TextView) findViewById(R.id.person_count_1);
        mCount2 = (TextView) findViewById(R.id.person_count_2);
        mCount3 = (TextView) findViewById(R.id.person_count_3);
        mCount4 = (TextView) findViewById(R.id.person_sms_remain);
        //寄件统计信息
        mTodaySendTV = (TextView) findViewById(R.id.person_today_send);
        mMonthSendTV = (TextView) findViewById(R.id.person_month_send);
        mTotalSendTV = (TextView) findViewById(R.id.person_total_send);
        //驿站头像
        mStorePhotoIV = (CircularImage) findViewById(R.id.person_store_photo);
        mStorePhotoIV.setOnClickListener(this);
        mVersion = (TextView) findViewById(R.id.version);
        try {
            PackageInfo packInfo = getActivityContext().getPackageManager().getPackageInfo(getActivityContext().getPackageName(), 0);
            String versionName = packInfo.versionName + "";
            mVersion.setText(versionName);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        // 邮票商城
        mStampShop = findViewById(R.id.person_stamp_shop);
        mStampShop.setOnClickListener(this);
        // 我的邮票
        mMyStamp = findViewById(R.id.person_my_stamp);
        mMyStamp.setOnClickListener(this);
        // 短信充值
        findViewById(R.id.person_sms_charge).setOnClickListener(this);
        // 我的二维码
        findViewById(R.id.pserson_scan_IV).setOnClickListener(this);
        //我的钱包
        findViewById(R.id.person_my_wallet).setOnClickListener(this);
        //驿站信息
        findViewById(R.id.station_info_tv).setOnClickListener(this);
        //我的活动
        TextView activeTV = (TextView) findViewById(R.id.person_my_active);
        activeTV.setOnClickListener(this);
        //邀请好友开通驿站
        findViewById(R.id.station_invate_tv).setOnClickListener(this);
        UserBean userBean = AppCache.getUser();
        //衡水
        if (!StringUtils.isEmpty(userBean.getCode()) && userBean.getCode().startsWith("318")) {
            activeTV.setVisibility(View.VISIBLE);
        } else {
            activeTV.setVisibility(View.GONE);
        }
        final View guildView = findViewById(R.id.take_my_guild);
        guildView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                guildView.setVisibility(View.GONE);
                SharedPref.setFirstOpen(Constants.isShowStorePhotoTip, false);
                return true;

            }
        });
        if (SharedPref.isFirstOpen(Constants.isShowStorePhotoTip)) {
            guildView.setVisibility(View.VISIBLE);
        }
        if (!isEmpty(AppCache.getUser().getHeadImage())) {
            GlideUtil.loadImage(getActivityContext(), AppCache.getUser().getHeadImage(), R.drawable.person_store_photo, mStorePhotoIV);
        } else {
            mStorePhotoIV.setImageResource(R.drawable.person_store_photo);
        }
    }

    private void setStationLevel() {
        try {
            // 驿站的信息
            TextView mStoreName = (TextView) findViewById(R.id.person_store_name);
            //驿站级别
            LinearLayout levelLayout = (LinearLayout) findViewById(R.id.level_ll);
            UserBean user = AppCache.getUser();
            if (null == user.getStationId() || isEmpty(user.getName())) {
                mStoreName.setText("驿站暂未开通");
            } else {
                mStoreName.setText(user.getName());
            }
            if (null == user.getStationId()) {
                levelLayout.setVisibility(View.GONE);
                mStampShop.setVisibility(View.GONE);
                mMyStamp.setVisibility(View.GONE);
            } else {
                levelLayout.setVisibility(View.VISIBLE);
                TextView levelName = (TextView) findViewById(R.id.station_level_name_tv);
                ImageView levelImage = (ImageView) findViewById(R.id.station_level_iv);
                if (user.getLevel() >= 0 && user.getLevel() < 10) {//初级
                    levelName.setText("(入门级)");
                    levelImage.setImageResource(R.drawable.my_rm_icon);
                } else if (user.getLevel() > 10 && user.getLevel() < 20) {//标准
                    levelName.setText("(标准级)");
                    levelImage.setImageResource(R.drawable.my_bz_icon);
                } else {//专业
                    levelName.setText("(专业级)");
                    levelImage.setImageResource(R.drawable.my_zyj_icon);
                }
                if (!StringUtils.isEmpty(user.getCode())
                        && (user.getCode().startsWith("010") || user.getCode().toLowerCase().startsWith("bj"))) {
                    mStampShop.setVisibility(View.VISIBLE);
                    mMyStamp.setVisibility(View.VISIBLE);
                } else {
                    mStampShop.setVisibility(View.GONE);
                    mMyStamp.setVisibility(View.GONE);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            //点击我的头像
            case R.id.person_store_photo:
                if (null == AppCache.getUser().getStationId()) {
                    showToast("您的驿站还没有成功开通，开通后即可查看驿站信息");
                    return;
                }
                baseDialog = DialogMgr.showStorePhoto(getActivityContext(), AppCache.getUser().getHeadImage(), this);
                break;
            //点击更新头像
            case R.id.update_photo_bt:
                intent = new Intent(getActivityContext(), PhotoCameraActivity.class);
                startActivityForResult(intent, 1005);
                if (baseDialog != null) {
                    baseDialog.dismiss();
                }
                break;
            //驿站信息
            case R.id.station_info_tv:
                if (null == AppCache.getUser().getStationId()) {
                    showToast("您的驿站还没有成功开通，开通后即可查看驿站信息");
                    return;
                }
                intent = new Intent(getActivityContext(), MyStationInfoActivity.class);
                intent.putExtra("type", 0);
                startActivity(intent);
                break;
            //我的二维码
            case R.id.pserson_scan_IV:
                if (null == AppCache.getUser().getStationId()) {
                    showToast("您的驿站暂未开通");
                    return;
                }
                startActivity(MyQRCodeActivity.class);
                break;
            //邮票商场
            case R.id.person_stamp_shop:
                if (null == AppCache.getUser().getStationId()) {
                    showToast("您的驿站暂未开通");
                    return;
                }
                startActivity(StampStoreActivity.class);
                break;
            //我的邮票
            case R.id.person_my_stamp:
                if (null == AppCache.getUser().getStationId()) {
                    showToast("您的驿站暂未开通");
                    return;
                }
                startActivity(CouponListActivity.class);
                break;
            // 短信充值
            case R.id.person_sms_charge:
                if (null == AppCache.getUser().getStationId()) {
                    showToast("您的驿站暂未开通");
                    return;
                }
                if (smsRemainCount == null) {
                    showLoadingDialog(null);
                    AppHttp.getInstance().takeSmsCount();
                } else {
                    intent = new Intent();
                    intent.setClass(getActivityContext(), SmsReChargeActivity.class);
                    intent.putExtra("data", smsRemainCount);
                    startActivity(intent);
                }
                break;
            //我的钱包
            case R.id.person_my_wallet:
                if (null == AppCache.getUser().getStationId()) {
                    showToast("您的驿站暂未开通");
                    return;
                }
                intent = new Intent();
                intent.setClass(getActivityContext(), MyWalletActivity.class);
                startActivity(intent);
                break;
            //我的活动
            case R.id.person_my_active:
                if (null == AppCache.getUser().getStationId()) {
                    showToast("您的驿站暂未开通");
                    return;
                }
                AppLogic.contextToActive(getActivityContext(), "com.shouhuobao.take.active.ActiveMainActivity");
                break;
            //邀请好友开通驿站
            case R.id.station_invate_tv:
                if (null == AppCache.getUser().getStationId()) {
                    showToast("您的驿站暂未开通");
                    return;
                }
                startActivity(StationInviteActivity.class);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 统计包裹数量
            case MsgID.take_query_count:
                final ReqResult<String> result2 = JSON.parser(msg.obj, String.class);
                if (checkLoginStatus(result2)) {
                    getActivityContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String[] strs = result2.getResult().split(",");
                            mCount1.setText(strs[0]);
                            mCount2.setText(strs[1]);
                            mCount3.setText(strs[2]);
                            mCount4.setText("剩余" + strs[3] + "条");
                            smsRemainCount = strs[3] + "," + strs[4];
                            //寄件统计
                            mTodaySendTV.setText(strs[5]);
                            mMonthSendTV.setText(strs[6]);
                            mTotalSendTV.setText(strs[7]);
                            mAccountMoney.setText(String.format(accountMoneyStr, strs[8]));
                        }
                    });
                } else {
                    showToast(result2.getMessage());
                }
                return true;
            // 查询数量
            case MsgID.take_sms_query_count:
                cancelLoadingDialog();
                // result格式为: "条数,单价"
                final ReqResult<String> result1 = JSON.parser(msg.obj, String.class);
                if (checkLoginStatus(result1)) {
                    getActivityContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            smsRemainCount = result1.getResult();
                            String[] strs = smsRemainCount.split(",");
                            mCount4.setText("剩余" + strs[0] + "条");
                            Intent intent = new Intent();
                            intent.setClass(getActivityContext(), SmsReChargeActivity.class);
                            intent.putExtra("data", result1.getResult());
                            startActivity(intent);
                        }
                    });
                } else {
                    showToast(result1.getMessage());
                }
                return true;
            //上传头像返回图片路径
            case MsgID.upload_image:
                ReqResult<?> reqResult = JSON.parser(msg.obj);
                if (checkLoginStatus(reqResult)) {
                    Object imageUrl = reqResult.getResult();
                    if (!isEmpty(imageUrl)) {
                        photoUrl = imageUrl + "";
                        AppHttp.getInstance().updateStorePhoto(imageUrl);
                    } else {
                        cancelLoadingDialog();
                        showToast("上传图片失败");
                    }
                } else {
                    cancelLoadingDialog();
                    showToast(reqResult.getMessage());
                }
                return false;
            //头像上传返回
            case MsgID.take_update_store_photo:
                cancelLoadingDialog();
                final ReqResult<?> result = JSON.parser(msg.obj);
                getActivityContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result)) {
                            UserBean userBean = AppCache.getUser();
                            userBean.setHeadImage(photoUrl);
                            AppCache.setUser(userBean);
                            Bitmap imageThumbnail = BitmapUtils.getImageThumbnail(localPhotoUrl, 150, 150);
                            if (imageThumbnail != null) {
                                mStorePhotoIV.setImageBitmap(imageThumbnail);
                            } else {
                                GlideUtil.loadImage(getActivityContext(), photoUrl, R.drawable.person_store_photo, mStorePhotoIV);
                            }
                        } else {
                            showToast(result.getMessage());
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && 1005 == requestCode) {
            String capturePath = data.getStringExtra("file");
            if (!Str.isEmpty(capturePath)) {
                localPhotoUrl = capturePath;
                showLoadingDialog("正在上传图片");
                AppHttp.getInstance().postFils(capturePath);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onStop() {
        super.onStop();
        isRequest2get = true;
    }

    @Override
    public void onDestroy() {
        if (baseDialog != null) {
            baseDialog.dismiss();
        }
        mhandler.removeMessages(1);
        super.onDestroy();
    }
}
